/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.ouertech.android.agm.lib.ui.base;

import android.app.Dialog;
import android.content.res.TypedArray;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.ui.R;
import com.ouertech.android.agm.lib.ui.widget.popup.PopupMenu;
import com.pnikosis.materialishprogress.ProgressWheel;

/**
 * @author : Zhenshui.Xia
 * @date : 2015/7/20.
 * @desc :
 */
public abstract  class BaseUIFragment extends BaseFragment
        implements View.OnClickListener {
    //标题居左
    private static final int TOOLBAR_TITLE_GRAVITY_LEFT = 0;
    //标题居中
    private static final int TOOLBAR_TITLE_GRAVITY_CENTER = 1;

    //界面构选项
    private long mOptions;
    //appbar自定义布局
    private int mAppCustomLayoutRes;
    //工具栏（标题栏）
    private Toolbar mToolbar;
    //标题位置
    private int mTitleGravity;
    //标题
    private TextView mTvTitle;
    //导航图标点击事件监听器
    private MenuItem.OnMenuItemClickListener mNavigationListener;
    //menu集合
    private SparseArray<MenuBase> mMenus;

    //
    private FrameLayout mFlContent;
    //数据加载中
    private ProgressWheel mPwLoading;
    //暂无数据提示
    private TextView mTvEmpty;
    //网络请求重试
    private TextView mTvRetry;
    //网络请求重试监听器
    private OnRetryListener mRetryListener;

    //等待对话框
    private Dialog mWaitDialog;

    private View mViewShadow;

    /**
     * 初始化appbar Toolbar
     */
    protected void initAppToobar(){

    }

    /**
     * 初始化Appbar custom
     */
    protected void initAppCustom() {

    }


    /**
     * 网络请求重试监听器
     */
    public interface OnRetryListener {
        //重试
        public void onRetry();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        //获取构造的界面结构
        mOptions = initOptions();

        //初始化menu集合，最多支持8个menu
        mMenus = new SparseArray<>(8);
        mMenus.put(R.id.res_id_menu_item0, null);
        mMenus.put(R.id.res_id_menu_item1, null);
        mMenus.put(R.id.res_id_menu_item2, null);
        mMenus.put(R.id.res_id_menu_item3, null);
        mMenus.put(R.id.res_id_menu_item4, null);
        mMenus.put(R.id.res_id_menu_item5, null);
        mMenus.put(R.id.res_id_menu_item6, null);
        mMenus.put(R.id.res_id_menu_item7, null);
    }

    /**
     * 初始化界面构造选项
     * @return
     */
    protected long initOptions() {
        return UIOptions.UI_OPTIONS_SCREEN_DEFAULT;
    }

    @Override
    protected View initBaseViews() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.res_activity_base_ui, null);

        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR
                | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM)) {
            ViewStub appbarStub = (ViewStub) view.findViewById(R.id.base_id_appbar_stub);
            appbarStub.setLayoutResource(R.layout.res_layout_base_appbar);
            appbarStub.inflate();

            //初始化appbar toolbar
            if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
                ViewStub toolbarStub = (ViewStub) view.findViewById(R.id.base_id_appbar_toolbar_stub);
                toolbarStub.setLayoutResource(R.layout.res_layout_base_appbar_toolbar);
                toolbarStub.inflate();

                mToolbar = (Toolbar) view.findViewById(R.id.base_id_appbar_toolbar);
                TypedArray a = mActivity.obtainStyledAttributes(R.style.res_style_toolbar_title_gravity,
                        R.styleable.Toolbar);
                mTitleGravity = a.getInt(R.styleable.Toolbar_titleGravity, TOOLBAR_TITLE_GRAVITY_LEFT);
                a.recycle();

                if (mTitleGravity == TOOLBAR_TITLE_GRAVITY_CENTER) {
                    mTvTitle = (TextView) view.findViewById(R.id.base_id_appbar_toolbar_title);
                } else {
                    //设置默认的toolbar title样式
                    mToolbar.setTitleTextAppearance(mActivity, R.style.res_style_toolbar_title_text);
                    //设置默认的toolbar subtitle样式
                    mToolbar.setSubtitleTextAppearance(mActivity, R.style.res_style_toolbar_subtitle_text);
                }

                mActivity.setSupportActionBar(mToolbar);
                mActivity.getSupportActionBar().setDisplayShowTitleEnabled(false);

                initAppToobar();
            }
        }

        //初始化appbar custom
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_CUSTIOM)) {
            initAppCustom();
            if(mAppCustomLayoutRes > 0) {
                ViewStub customStub = (ViewStub) view.findViewById(R.id.base_id_appbar_custom_stub);
                customStub.setLayoutResource(mAppCustomLayoutRes);
                customStub.inflate();
            }
        }

        //显示内容
        if(withOption(UIOptions.UI_OPTIONS_CONTENT_CUSTOM)) {
            ViewStub contentStub = (ViewStub) view.findViewById(R.id.base_id_content_stub);
            contentStub.setLayoutResource(R.layout.res_layout_base_content_custom);
            contentStub.inflate();

            mViewShadow = view.findViewById(R.id.base_id_content_shadow_top);

            mFlContent = (FrameLayout) view.findViewById(R.id.base_id_content_root);
            mPwLoading = (ProgressWheel) view.findViewById(R.id.base_id_content_progress);
            mTvEmpty = (TextView) view.findViewById(R.id.base_id_content_empty);
            mTvRetry = (TextView) view.findViewById(R.id.base_id_content_retry);

            mTvRetry.setOnClickListener(this);
        }

        if(mViewShadow != null) {
            if (withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
                mViewShadow.setVisibility(View.VISIBLE);
            } else {
                mViewShadow.setVisibility(View.GONE);
            }
        }

        return view;
    }


    /**
     * 设置标题
     * @param title
     */
    public void setTitle(String title) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
            if(mTitleGravity == TOOLBAR_TITLE_GRAVITY_CENTER) {
                if(mTvTitle != null) {
                    mTvTitle.setText(title);
                }
            } else {
                if(mToolbar != null ) {
                    mToolbar.setTitle(title);
                }
            }
        }
    }

    /**
     * 设置标题
     * @param txtRes
     */
    public void setTitle(@StringRes int txtRes) {
        setTitle(getString(txtRes));
    }

    /**
     * 设置子标题,居中模式暂不支持子标题
     * @param title
     */
    public void setSubTitle(String title) {
        if(withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)
                && mTitleGravity == TOOLBAR_TITLE_GRAVITY_LEFT
                && mToolbar != null) {
            mToolbar.setSubtitle(title);
        }
    }

    /**
     * 设置子标题
     * @param txtRes
     */
    public void setSubTitle(@StringRes int txtRes) {
        setSubTitle(getString(txtRes));
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param imgRes
     */
    public void setNavigation(@DrawableRes int imgRes) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));

        MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                mActivity.finish();
                return false;
            }
        };

        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param drawable
     */
    public void setNavigation(Drawable drawable) {
        MenuItem.OnMenuItemClickListener listener = new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                mActivity.finish();
                return false;
            }
        };

        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param imgRes
     * @param listener
     */
    public void setNavigation(@DrawableRes int imgRes, MenuItem.OnMenuItemClickListener listener) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));
        setNavigation(drawable, listener);
    }

    /**
     * 显示左边导航控件和其默认点击事件监听器（退出界面）
     * @param drawable
     * @param listener
     */
    public void setNavigation(Drawable drawable, MenuItem.OnMenuItemClickListener listener) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
            return;
        }

        if(mToolbar != null) {
            mToolbar.setNavigationIcon(drawable);
        }

        mNavigationListener = listener;
    }

    /**
     * 显示标题栏logo
     * @param imgRes
     */
    public void setLogo(@DrawableRes int imgRes) {
        BitmapDrawable drawable = new BitmapDrawable(getResources(),
                BitmapFactory.decodeResource(getResources(), imgRes));
        setLogo(drawable);
    }

    /**
     * 显示标题栏logo
     * @param drawable
     */
    public void setLogo(Drawable drawable) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR)) {
            return;
        }

        if(mToolbar != null) {
            mToolbar.setLogo(drawable);
        }
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();

        for (int i = 0; i < mMenus.size(); i++) {
            MenuBase value = mMenus.valueAt(i);

            if (value != null) {
                if(value instanceof MenuTxt) {//添加文本menu
                    MenuTxt elem = (MenuTxt)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuImg) {//添加图片menu
                    MenuImg elem = (MenuImg)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setIcon(elem.getIcon());
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuSearch) {//添加搜索menu
                    MenuSearch elem = (MenuSearch)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    SearchView svSearch = new SearchView(mActivity);
                    svSearch.setOnQueryTextListener(elem.getListener());
                    item.setActionView(svSearch);
                    item.setShowAsAction(elem.getShowAsAction());
                } else if(value instanceof MenuPopup) {//添加popup menu
                    MenuPopup elem = (MenuPopup)value;
                    MenuItem item = menu.add(Menu.NONE,
                            elem.getMenuId(), elem.getOrder(), elem.getTitle());
                    item.setIcon(elem.getIcon());
                    item.setShowAsAction(elem.getShowAsAction());
                }
            }
        }

        super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        MenuBase value = mMenus.get(itemId);

        if(android.R.id.home == itemId) {
            if(mNavigationListener != null) {
                mNavigationListener.onMenuItemClick(item);
            }
        } else {
            if (value != null) {
                if (value instanceof MenuTxt) {//触发点击文本menu
                    MenuTxt elem = (MenuTxt) value;
                    MenuItem.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        listener.onMenuItemClick(item);
                    }
                } else if (value instanceof MenuImg) {//触发点击图片menu
                    MenuImg elem = (MenuImg) value;
                    MenuItem.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        listener.onMenuItemClick(item);
                    }
                } else if (value instanceof MenuPopup) {//触发打开popupmenu
                    MenuPopup elem = (MenuPopup) value;
                    View view = mToolbar.findViewById(elem.getMenuId());
                    PopupMenu popup = new PopupMenu(mActivity, view);
                    MenuInflater inflater = popup.getMenuInflater();
                    inflater.inflate(elem.getMenuRes(), popup.getMenu());
                    popup.show();

                    PopupMenu.OnMenuItemClickListener listener = elem.getListener();
                    if (listener != null) {
                        popup.setOnMenuItemClickListener(listener);
                    }
                }
            }
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 添加menu
     * @param menu
     */
    public void addMenu(@NonNull MenuBase menu) {
        if(!withOption(UIOptions.UI_OPTIONS_APPBAR_TOOLBAR) ) {
            return;
        }

        if(menu != null && mMenus.get(menu.getMenuId()) == null) {
            for (int i = 0; i < mMenus.size(); i++) {
                int key = mMenus.keyAt(i);
                if (mMenus.get(key) == null) {
                    menu.setMenuId(key);
                    mMenus.put(key, menu);
                    mActivity.invalidateOptionsMenu();
                    break;
                }
            }
        }
    }


    /**
     * 隐藏menu
     * @param menu
     */
    public void hideMenu(MenuBase menu){
        if(menu != null) {
            hideMenu(menu.getMenuId());
            menu.setMenuId(0);
        }
    }

    /**
     * 隐藏menu
     * @param menuId
     */
    public void hideMenu(int menuId){
        if(mMenus.get(menuId) != null) {
            mMenus.put(menuId, null);
            mActivity.invalidateOptionsMenu();
        }
    }

    /**
     * 设置视图
     * @param layoutResId
     */
    public void setContentView(int layoutResId) {
        if(layoutResId > 0 ) {
            View view = LayoutInflater.from(mActivity).inflate(layoutResId, null);
            setContentView(view);
        }
    }

    /**
     * 设置视图
     * @param view
     */
    public void setContentView(View view) {
        if(view != null && mFlContent != null) {
            mFlContent.addView(view,
                    FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
        }
    }

    /**
     * 根据资源id找到视图
     * @param id
     * @return
     */
    public View findViewById(int id) {
        return mFlContent.findViewById(id);
    }



    /**
     * 显示空数据文本提示
     * @param txtRes
     */
    public void setEmptyText(@StringRes int txtRes) {
        setEmptyText(getString(txtRes));
    }

    /**
     * 显示空数据文本提示
     * @param emptyText
     */
    public void setEmptyText(String emptyText) {
        if(mFlContent != null) mFlContent.setVisibility(View.GONE);
        if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
        if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
        if(mTvEmpty != null) {
            mTvEmpty.setVisibility(View.VISIBLE);
            mTvEmpty.setText(emptyText);
        }
    }

    /**
     * 隐藏空数据文本提示
     */
    public void hideEmptyText() {
        if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
        if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
    }

    /**
     * 显示(隐藏)重试图标
     */
    public void setRetry(boolean enabled) {
        if (enabled) {
            if(mFlContent != null) mFlContent.setVisibility(View.GONE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.VISIBLE);
            if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
        } else {
            if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
        }
    }

    /**
     * 设置重试事件
     * @param listener
     */
    public void setOnRetryListener(OnRetryListener listener) {
        this.mRetryListener = listener;
    }

    /**
     * 显示(隐藏)加载过程
     */
    public void setLoading(boolean enabled) {
        if (enabled) {
            if(mFlContent != null) mFlContent.setVisibility(View.GONE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.VISIBLE);
            if(mTvRetry != null) mTvRetry.setVisibility(View.GONE);
            if(mTvEmpty != null) mTvEmpty.setVisibility(View.GONE);
        } else {
            if(mFlContent != null) mFlContent.setVisibility(View.VISIBLE);
            if(mPwLoading != null) mPwLoading.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.base_id_content_retry) {
            retry();
        }
    }

    /**
     * 显示等待对话框
     * @param enabled
     */
    public void setWaitingDialog(boolean enabled) {
        if(enabled) {
            if(mWaitDialog == null) {

                mWaitDialog = new AlertDialog.Builder(mActivity, R.style.res_theme_dialog_waiting)
                        .setView(R.layout.res_layout_base_progress)
                        .show();
                mWaitDialog.setCanceledOnTouchOutside(false);
            } else if(!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
        } else {
            if(mWaitDialog != null && mWaitDialog.isShowing()) {
                mWaitDialog.cancel();
            }
        }
    }



    /**
     * 是否有当前界面构造选项
     * @param option
     * @return
     */
    private boolean withOption(long option) {
        return (mOptions & option) != 0;
    }

    /**
     * 重试加载
     */
    private void retry() {
        if (mRetryListener != null) {
            mRetryListener.onRetry();
        }
    }


    /**
     * 设置appbar通用布局的layout
     * @param layoutRes
     */
    public void setAppCustomLayout(@LayoutRes int layoutRes) {
        this.mAppCustomLayoutRes = layoutRes;
    }
}
